<!-- 孔德嘉 群聊消息 -->
<template>
  <div class="all">
    <el-card class="card" body-style="{height:100%}">
      <el-row class="chat" :gutter="20">
        <!-- 群聊列表 -->
        <el-col class="chatList" :span="4">
          <!-- 创建群聊 -->
          <el-button
            class="createGroup"
            style="margin-bottom: 20px"
            @click="toCreateGroup"
          >
            创建群聊
          </el-button>
          <!-- <el-button
            class="createGroup"
            style="margin-left: 0px; margin-bottom: 20px"
            @click="isJoinGroup = true"
          >
            加入群聊
          </el-button> -->
          <el-button
            class="createGroup"
            style="margin-left: 0px; position: relative"
            @click="toJoinGroupAudit"
          >
            入群审核
            <span
            v-if="num !=''"
              style="
                color: rgb(255, 255, 255);
                border-radius: 50%;
                display: inline-block;
                width: 20px;
                height: 20px;
                background: red;
                line-height: 20px;
                text-align: center;d
                position: absolute;
                left: 70%;
                top: 10px;
              "
              >{{ num > 99 ? "99" : num }}</span
            >
          </el-button>
          <!-- 群聊列表 v-show="joinNum != 0" -->
          <ul class="list">
            <li
              v-for="(item, index) in groupList"
              :key="index"
              @click="toChat(item, index)"
              :class="[nowInGroup == item ? 'active' : '']"
            >
              <!-- 未读数 -->
              <div v-show="item.unReadNum != 0" class="unReadNum">
                {{ item.unReadNum > 99 ? "99+" : item.unReadNum }}
              </div>
              <!-- 群聊相片 -->
              <el-image
                style="
                  vertical-align: middle;
                  width: 50px;
                  height: 50px;
                  display: inline-block;
                  border-radius: 20%;
                "
                :src="$imageUrl + item.groupImgId"
              ></el-image>
              <!-- 群名 -->
              <div class="groupListText">
                <p class="gropName">{{ item.groupName }}</p>
                <!-- 最后更新时间 -->
                <p class="lastTime">{{ item.lastMessageTime }}</p>
              </div>
            </li>
          </ul>
        </el-col>
        <!-- 群聊聊天框  :isSocketOpen="isSocketOpen"
            @sendMessage="sendMessage" -->
        <el-col :span="20">
          <GroupChat
            :nowInGroup="nowInGroup"
            :newMsg="newMsg"
            :recallUuid="recallUuid"
          ></GroupChat>
        </el-col>
      </el-row>
    </el-card>

    <!-- 搜索群聊弹窗 -->
    <el-dialog title="搜索群聊" :visible.sync="isJoinGroup" width="30%">
      <el-row :gutter="20">
        <el-col :span="19"
          ><el-input v-model="queryGroup" placeholder="请输入内容"></el-input>
          <div class="result" v-if="showQueryGroupResult">
            <div v-if="queryGroupData != null">
              <!-- 群聊相片 -->
              <el-image
                class="resultGroupImg"
                :src="$imageUrl + queryGroupData.groupImgId"
              ></el-image>
              <!-- 群名 -->
              <p class="resultGroupName">
                {{ queryGroupData.groupName }}
              </p>
              `
              <el-button
                v-if="!isExist"
                class="queryButton"
                @click="toJoinGroup(queryGroupData)"
                >申请加群
              </el-button>
            </div>
            <!-- 没查询到结果 -->
            <div v-else class="resultNopty">无</div>
          </div></el-col
        >
        <el-col :span="5"
          ><el-button @click="toQueryGroup">搜索</el-button></el-col
        >
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isJoinGroup = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import GroupChat from "../../components/GroupChat.vue";

export default {
  name: "groupIndex",
  components: { GroupChat },
  data() {
    return {
      //被撤回的消息id
      recallUuid: "0",
      delailHouse: false,
      //入群申请未读数
      joinNum: 0,
      //入群申请未读数
      num: 0,
      //接收到的新消息
      newMsg: {},
      //群聊搜索到的结果是否已经加入
      isExist: false, //默认是没有
      //群聊的搜索结果
      showQueryGroupResult: false,
      //获取到的群聊对象
      queryGroupData: "",
      //查询群聊
      queryGroup: "983888840",
      //加入群聊是否开启
      isJoinGroup: false,
      //切换的当前item
      nowInGroup: {},
      imageUrl: "",
      //群聊列表
      groupList: [],
    };
  },

  computed: {
    userId() {
      return this.$store.state.user.userId;
    },
  },
  beforeDestroy() {
    window.removeEventListener("onmessageWS", this.getsocketData);
  },
  mounted() {
    window.addEventListener("onmessageWS", this.getsocketData);
    this.num = 0;
    //获取群聊列表
    this.getGroupList();
    // 获取未处理的入群审核
    this.getUnReadJoinGroup();
    //监听创建群聊
    this.$on("createGroup", (groupId) => {
      let message = {
        type: "create_group",
        grouId: groupId,
      };
      this.ws.send(JSON.stringify(message));
    });
  },
  watch: {
    num(oldValue, newValue) {
      // console.log("num", oldValue, newValue);
    },
  },
  methods: {
    //接收websocket消息
    getsocketData(e) {
      const data = e && e.detail.data;
      let infos = JSON.parse(data);
      //判断信息的类型
      switch (infos.type) {
        //接收消息
        case "group_message":
          this.handleGroupMessage(infos);
          break;
        //加入群聊
        case "to_join_group":
          this.num++;
          // this.handletoJoinGroup(infos);
          break;
        //撤回消息
        case "recall":
          this.handleRecallGroup(infos);
          break;
      }
    },
    // 获取未处理的入群审核数量
    getUnReadJoinGroup() {
      this.$axios
        .get("/joinGroup/getUnReadJoinGroup", {
          params: { createUserId: this.userId },
        })
        .then((res) => {
          if (res.data.flag) {
            // console.log("获取未处理的入群审核数量");
            this.num = res.data.data;
          } else {
            this.$message.warning(res.data.code);
          }
        })
        .catch((err) => {
          this.$message.warning(err);
        });
    },
    //去审核入群申请
    toJoinGroupAudit() {
      // 通过vuex将数据存储在store中
      let value = {
        title: "审核入群申请",
        url: "/group/JoinGroupAudit",
      };
      this.$store.commit("mutationSelectTags", value);
      this.$router.push({ path: "/group/JoinGroupAudit" });
    },
    //去聊天
    toChat(item, index) {
      //点击切换chat页面
      this.nowInGroup = item;
      //未读数清楚
      this.groupList[index].unReadNum = 0;
    },
    //加入群聊
    toJoinGroup(item) {
      // //查询群聊 并查询是否添加过
      let data = {
        userId: this.userId,
        groupId: item.id,
      };
      this.$axios
        .post("/joinGroup/toJoinGroupSys", data)
        .then((res) => {
          if (res.data.flag) {
            //刷新index页面
            this.getGroupList();
            //关闭 添加弹窗
            this.isJoinGroup = false;
          } else {
            this.$message.warning(res.data.code);
          }
        })
        .catch((err) => {
          this.$message.warning(err);
        });
    },
    //去查询群聊
    toQueryGroup() {
      // 判断条件是不是空值
      if (this.queryGroup.trim() == "") {
        this.$message.warning("请输入内容");
        return;
      }
      //查询群聊 并查询是否添加过
      this.$axios
        .get("/group/queryGroupByNum", {
          params: {
            groupNum: this.queryGroup,
            userId: this.userId,
            type: "sys",
          },
        })
        .then((res) => {
          if (res.data.flag) {
            this.queryGroupData = res.data.data.group;
            this.isExist = res.data.data.isExist;
            this.showQueryGroupResult = true;
          } else {
            this.$message.warning(res.data.code);
          }
        })
        .catch((err) => {
          this.$message.warning(err);
        });
    },

    // 数组置顶__
    toFirst({ arr, index }) {
      if (index != 0) {
        arr.unshift(arr.splice(index, 1)[0]);
      }
      return arr;
    }, //接收到撤回消息
    handleRecallGroup(data) {
      //判断撤回该消息的人是不是自己
      if (data.fromId == this.userId && data.userType == 0) {
        //撤回消息的人是我自己
        return;
      }
      this.recallUuid = data.uuid;
    },
    //接收到入群申请
    handletoJoinGroup() {
      this.joinNum = 232;
    },
    //更新当前群聊消息
    updateChatToGroup(data) {
      this.newMsg = data;
    },
    //接收群聊消息
    handleGroupMessage(data) {
      //判断是否为当前聊天页面的群聊发送的消息
      let send = this.nowInGroup.groupId == data.toId;
      //判断是不是自己发送的
      let isMysend = this.userId == data.fromId;
      // 更新会话列表
      let groupList = this.groupList;
      const i = groupList.findIndex((v) => v.groupId === data.toId);
      if (i < 0) {
        return;
      }
      let item = groupList[i];
      const inputString = data.createTime;
      // 找到时间部分的起始位置和结束位置
      const startTimeIndex = inputString.indexOf(" ") + 1; // 找到空格后的第一个字符
      const endTimeIndex = startTimeIndex + 5; // 从起始位置向后截取5个字符，即 HH:mm 部分的结束位置

      // 使用substring方法截取时间部分
      const timeString = inputString.substring(startTimeIndex, endTimeIndex);
      item.lastMessageTime = timeString;
      //如果是当前群聊更新会话列表
      if (!isMysend & send) {
        this.newMsg = data;
      } else if (!send & !isMysend) {
        //如果不是的话更新未读数
        // 不是当前页面发出的消息 未读数++
        item.unReadNum++;
      }
      // 置顶当前会话
      this.groupList = this.toFirst({
        arr: groupList,
        index: i,
      });
    },
    //获取群聊列表
    getGroupList() {
      this.$axios
        .get("/group/getGroupByCreateUserId", {
          params: { createUserId: this.userId },
        })
        .then((res) => {
          if (res.data.flag) {
            this.groupList = res.data.data;
            if (this.groupList.length > 0) {
              // 子组件默认显示第一个
              this.nowInGroup = this.groupList[0];
            } else {
              this.nowInGroup = null;
            }
          } else {
            this.$message.warning(res.data.code);
          }
        })
        .catch((err) => {
          this.$message.warning(err);
        });
    },
    //创建群聊
    toCreateGroup() {
      // 通过vuex将数据存储在store中
      let value = {
        title: "创建群聊",
        url: "/group/ToCreateGroup",
      };
      this.$store.commit("mutationSelectTags", value);
      this.$router.push({ path: "/group/ToCreateGroup" });
    },
  },
};
</script>

<style scoped>
.all {
  height: 94%;
  margin-top: 1%;
  width: 96%;
  margin-left: 2%;
}
.card {
  height: 100%;
}
.chat {
  height: 100%;
}
.chat > div {
  height: 100%;
}
.chatList {
  border-right: 2px solid #efefef;
}
/deep/.el-card__body {
  height: calc(100% - 40px);
}
.createGroup {
  border: 1px solid #2cd3b5;
  color: #2cd3b5;
  width: 100%;
  height: 40px;
}
.list {
  margin-top: 20px;
  overflow: auto;
  height: calc(100% - 160px);
}
.list > li {
  width: calc(100% - 20px);
  list-style: none;
  height: 50px;
  padding: 10px;
  position: relative;
  margin-bottom: 10px;
}
.list > li:hover {
  background: #efefef;
}
.unReadNum {
  position: absolute;
  left: 50px;
  top: 5px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  text-align: center;
  line-height: 18px;
  color: #fff;
  background-color: red;
  z-index: 9;
}
.gropInfo {
  display: inline-block;
  height: 50px;
  margin-left: 20px;
  vertical-align: middle;
}
.gropName {
  display: block;
  margin-left: 10px;
  width: 86px;
  font-weight: 700;
  font-size: 14px;
}
.lastTime {
  font-size: 14px;
  font-weight: 400;
  float: right;
  color: #bbbbbb;
  letter-spacing: -1px;
  vertical-align: bottom;
  margin-top: 16px;
}
.unReadNo {
  display: none;
}
.groupListText {
  height: 50px;
  display: inline-block;
  width: calc(100% - 50px);
  vertical-align: middle;
}
.list .active {
  background: #efefef;
}
.result {
  transform: translateY(-2px);
  padding: 10px 0;
  border-radius: 0px 0px 20px 20px;
  border-left: 1px solid #dcdfe6;
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
}
.resultGroupName {
  margin-left: 20px;
  height: 50px;
  line-height: 50px;
  display: inline-block;
  vertical-align: top;
  font-weight: 700;
}
.resultGroupImg {
  width: 50px;
  height: 50px;
  display: inline-block;
  border-radius: 20%;
  margin-left: 20px;
}
.resultNopty {
  margin: 0 auto;
  text-align: center;
  font-weight: 500;
  font-size: 18px;
  margin: 14px 0;
}
.queryButton {
  vertical-align: top;
  float: right;
  margin-right: 20px;
  padding: 0 10px;
  margin-top: 8px;
  height: 36px;
  line-height: 36px;
}
</style>